package logic

import (
	"context"
	"fmt"

	"server_1.0/service/result/internal/svc"
	"server_1.0/service/result/result"
	"server_1.0/util"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryLogic {
	return &QueryLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *QueryLogic) Query(in *result.QueryReq) (*result.QReps, error) {
	code := util.Success
	usersHandle := make([]*result.Reps, 0)
	count := 0
	if in.Pno != "" && in.Sno == "" {
		pnos, err := l.svcCtx.ResultModel.FindPno(l.ctx, in.Pno)
		fmt.Println(pnos)
		if err != nil {
			code = util.NoFoundError
		} else {
			for _, item := range pnos {
				usersHandle = append(
					usersHandle,
					&result.Reps{
						Code: int64(code),
						Time: item.Etime,
						Sno:  item.Rsno,
						Pno:  item.Rpno,
						Ans:  item.Rans,
					})
				count += 1
			}
		}
	} else if in.Pno == "" && in.Sno != "" {
		snos, err := l.svcCtx.ResultModel.FindSno(l.ctx, in.Sno)
		if err != nil {
			code = util.NoFoundError
		} else {
			for _, item := range snos {
				usersHandle = append(
					usersHandle,
					&result.Reps{
						Code: int64(code),
						Time: item.Etime,
						Sno:  item.Rsno,
						Pno:  item.Rpno,
						Ans:  item.Rans,
					})
				count += 1
			}
		}
	} else if in.Pno != "" && in.Sno != "" {
		_, err1 := l.svcCtx.ResultModel.FindOne(l.ctx, in.Sno)
		if err1 != nil {
			code = util.NoFoundError
		} else {
			res, err2 := l.svcCtx.ResultModel.FindTwo(l.ctx, in.Pno)
			if err2 != nil {
				code = util.NoFoundError
			} else {
				usersHandle = append(
					usersHandle,
					&result.Reps{
						Code: int64(code),
						Time: res.Etime,
						Sno:  res.Rsno,
						Pno:  res.Rpno,
						Ans:  res.Rans,
					})
				count += 1
			}
		}
	} else {
		res, _ := l.svcCtx.ResultModel.FindAll(l.ctx)
		for _, item := range res {
			usersHandle = append(
				usersHandle,
				&result.Reps{
					Code: int64(code),
					Time: item.Etime,
					Sno:  item.Rsno,
					Pno:  item.Rpno,
					Ans:  item.Rans,
				})
			count += 1
		}
	}

	return &result.QReps{
		Count: int64(count),
		QRs:   usersHandle,
	}, nil
}
